//app.js
App({
  globalData: {
    BASE_URL: "https://chenborui.xyz:5443/api",
    WS_BASE_URL: "wss://chenborui.xyz:5443/ws",
    // BASE_URL: "https://localhost:5443/api",
    // WS_BASE_URL: "wss://localhost:5443/ws",
    STORAGE_NAME: 'token',
    TOKEN: null,
    isLogin: false,
    socketTask: null,
    qrCodeInterval: null,
    userInfo: {
    },
    is401: false      //是否已经有401弹窗
  },
  onLaunch: function() {
    this.judgeLoginStatus(()=>{})
  },
  //判断是否登录
  judgeLoginStatus(success){
    let that = this
    wx.getStorage({
      key: this.globalData.STORAGE_NAME,
      success(res) {
        that.globalData.TOKEN = 'Bearer ' + res.data    //设置token
        that.globalData.isLogin = true
        
        that.requestUserInfo(()=>{
          that.connectSocket()    //连接websocket
          success()
          console.log(that.globalData.isLogin = true)
        })
      }
    })
  },

  requestUserInfo(success){
    wx.showLoading({
      title: '加载中',
    });
    // 提交数据
    let that = this
    wx.request({
      url: that.globalData.BASE_URL + "/getInfo",
      data: {
      },
      header: {
        'content-type': 'application/json',
        'Authorization': this.globalData.TOKEN
      },
      success(res) {
        res = that.responseInterceptor(res)
        if (res === undefined) return;
        that.globalData.userInfo = res.data
        wx.hideLoading();
        success()
      }

    })
  },

  logout() {
    wx.request({
      url: this.globalData.BASE_URL + "/logout",
      method: 'post',
      header: {
        'content-type': 'application/json',
        'Authorization': this.globalData.TOKEN
      },
      success(res) { }
    })
    this.clearInfo()
  },
  clearInfo() {
    this.globalData.isLogin = false
    this.globalData.TOKEN = ''
    this.globalData.userInfo = {}
    wx.clearStorageSync()
    //清除定时任务
    clearInterval(this.globalData.qrCodeInterval);
    this.globalData.qrCodeInterval = null
    //退出websocket连接
    this.globalData.socketTask.onClose();
    this.globalData.socketTask = null
  },

  //websocket连接
  connectSocket() {
    let userId =  this.globalData.userInfo.userId
    let _this = this;
    let socketTask = wx.connectSocket({
      url: this.globalData.WS_BASE_URL + '/' + userId
    });

    this.globalData.socketTask = socketTask

    socketTask.onOpen(() => {
      console.log("websocket连接成功")
    })

    socketTask.onClose(() => {
      console.log("websocket连接已断开")
    })

    socketTask.onMessage(function (res) {
      // console.log(res.data)
      let data = JSON.parse(res.data)
      if(data.type === 'message'){
        wx.showModal({
          title: '新消息：' + data.data.title,
          content: data.data.content,
          confirmText: '前往查看',
          success(res) {
            if (res.confirm) {
              wx.showLoading({
                title: '加载消息中',
              });
              wx.switchTab({
                url: '/pages/message/message',
                complete: () => {
                  wx.hideLoading();
                }
              })
            }
          }
        })
      }else if(data.type === 'record'){
        wx.showLoading({
          title: '加载扫描结果中',
        });
         wx.navigateTo({
          url: '/pages/home/scanResult/scanResult?data=' + res.data,
           complete: () => {
            wx.hideLoading();
          }
        })
      }
    });
  },

  //响应拦截器
  responseInterceptor(res){
    let that = this

    if(res.data.code === 401 && !this.globalData.is401){
      this.globalData.is401 = true  //防止下一个弹窗
      console.log("登录状态已过期")

      wx.hideLoading();
      wx.showModal({
        title: '系统提示',
        content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
        confirmText: '前往登录',
        success(res) {
          that.globalData.is401 = false
          if (res.confirm) {
            console.log("前往登录")
            that.clearInfo()
            wx.showLoading({
              title: '跳转中...',
            });
            wx.navigateTo({
              url: '/pages/login/index/index',
              complete: () => {
                wx.hideLoading();
              }
            })
          }

        }
      })
    }

    if (res.data.code !== 200){
      wx.hideLoading();
      wx.showToast({
        title: res.data.msg,
        icon: 'none',
        duration: 1500
      });
    }else{
      return res.data
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.globalData.socketTask.onClose();
  }
})